//
//  DDAlertWindow.m
//  DingDongZP
//
//  Created by 王威 on 16/3/18.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDAlertWindow.h"

@implementation DDAlertWindow
- (instancetype)initSharedWindow
{
    self = [super init];
    if (self) {
        self.windowLevel = UIWindowLevelAlert;
        self.backgroundColor = [UIColor clearColor];
        self.frame = [UIScreen mainScreen].bounds;
        
        self->_appKeyWindow = [self keyWindow];
    }
    return self;
}

- (void)resignKeyWindow
{
    if (self.subviews.count == 0) {
        [super resignKeyWindow];
        [[self keyWindow] makeKeyWindow];
        self.hidden = YES;
    }
}

#pragma mark - Public

+ (instancetype)sharedWindow
{
    static DDAlertWindow *_sharedWindow = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedWindow = [[super alloc] initSharedWindow];
    });
    return _sharedWindow;
}

- (void)showView:(UIView *)view
{
    if ([view isKindOfClass:[UIView class]]) {
        [self addSubview:view];
        [self makeKeyAndVisible];
    }
}

- (void)dismissView:(UIView *)view
{
    if ([view isKindOfClass:[UIView class]]) {
        [view removeFromSuperview];
        [self resignKeyWindow];
    }
}

- (void)dismissAll
{
    [self removeAllSubviews];
    [self resignKeyWindow];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    UIView *view = [super hitTest:point withEvent:event];
    if (view == self) {
        UIView *lastView = self.subviews.lastObject;
        if (lastView) {
            return lastView;
        }
    }
    return view;
}

- (AppDelegate *)appDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (UIWindow *)keyWindow
{
    return [[self appDelegate] window];
}

@end
